<template>
  <div style="border: 1px solid #ccc;">
    <div ref="toolbarContainer" style="border-bottom: 1px solid #ccc"></div>
    <div ref="editorContainer" style="height: 500px;"></div>
  </div>
</template>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<script>
import { createEditor, createToolbar } from '@wangeditor/editor';

export default {
  name: 'WangEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    uploadImgServer: {
      type: String,
      default: ''
    }
  },
  model: {
    prop: 'value',
    event: 'input'
  },
  data() {
    return {
      editor: null,
    }
  },
  mounted() {
    const editorConfig = {
      placeholder: '请输入内容...',
      onChange: (editor) => {
        this.$emit('input', editor.getHtml());
      },
      MENU_CONF: {
        uploadImage: {
          server: this.uploadImgServer,
          fieldName: 'file',
          customInsert(res, insertFn) {
            // res 是后端返回的整个 JSON 对象
            if (res.code === 200 && res.data?.url) {
              // 成功时调用 insertFn 插入图片
              insertFn(res.data.url);
            } else {
              alert('上传失败：' + res.msg);
            }
          },

          // 单个文件最大体积限制，默认为 2M
          maxFileSize: 1 * 1024 * 1024, // 1MB

          customUpload: (file, insertFn) => {
            const reader = new FileReader();

            reader.onload = (e) => {
              const image = new Image();
              image.src = e.target.result;

              image.onload = () => {
                const MAX_WIDTH = 2000;
                const MAX_HEIGHT = 768;

                // 判断是否过大
                if (image.width > MAX_WIDTH || image.height > MAX_HEIGHT) {
                  const shouldContinue = confirm(
                    `图片尺寸过大，请将图片缩放为 50% 或 30% 后再发布。\n\n仍要继续上传吗？`
                  );

                  if (!shouldContinue) {
                    return; // 用户取消上传
                  }
                }

                // 不管是否过大，都允许上传
                const formData = new FormData();
                formData.append('file', file);

                fetch(this.uploadImgServer, {
                  method: 'POST',
                  body: formData
                })
                  .then(res => res.json())
                  .then(res => {
                    if (res.code === 200 && res.data?.url) {
                      insertFn(res.data.url);
                    } else {
                      alert('上传失败：' + res.msg);
                    }
                  })
                  .catch(() => alert('上传出错'));
              };
            };

            reader.readAsDataURL(file);
          },

          // 最多可上传文件数，默认 100
          maxNumberOfFiles: 10,

          // 显式设置 Accept 头
          headers: {
            Accept: 'application/json, text/plain, */*'
          },

          // 是否将 meta 拼接到 url 参数中
          metaWithUrl: false,

        }
      }
    };

    const editor = createEditor({
      selector: this.$refs.editorContainer,
      html: this.value,
      config: editorConfig,
      mode: 'default',
    });

    const toolbarConfig = {};

    createToolbar({
      editor,
      selector: this.$refs.toolbarContainer,
      config: toolbarConfig,
      mode: 'default',
    });

    this.editor = Object.seal(editor);
  },
  watch: {
    value(val) {
      if (this.editor && val !== this.editor.getHtml()) {
        this.editor.setHtml(val);
      }
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
    }
  }
}
</script>
